package com.ruoyi.report.controller;

import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.mchange.lang.LongUtils;
import com.ruoyi.agent.domain.SysAgent;
import com.ruoyi.agent.mapper.SysAgentMapper;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.order.Utils.OrderUtils;
import com.ruoyi.order.domain.SysOrderOne;
import com.ruoyi.order.service.ISysOrderOneService;
import com.ruoyi.packages.domain.SysPackage;
import com.ruoyi.packages.mapper.SysPackageMapper;
import com.ruoyi.report.domain.ReportExportVO;
import com.ruoyi.report.domain.SysReportVO;
import com.ruoyi.report.mapper.SysReportDetailsMapper;
import com.ruoyi.store.domain.SysStore;
import com.ruoyi.store.mapper.SysStoreMapper;
import com.ruoyi.system.mapper.SysDeptMapper;
import io.swagger.models.auth.In;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.report.domain.SysReportDetails;
import com.ruoyi.report.service.ISysReportDetailsService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 报告列表Controller
 *
 * @author ruoyi
 * @date 2024-06-28
 */
@RestController
@RequestMapping("/report/reportDetails")
public class SysReportDetailsController extends BaseController
{
    @Autowired
    private ISysReportDetailsService sysReportDetailsService;

    @Autowired
    private ISysOrderOneService orderOneService;

    @Autowired
    private SysReportDetailsMapper reportDetailsMapper;

    @Autowired
    private SysPackageMapper packageMapper;

    @Autowired
    private SysDeptMapper deptMapper;

    @Autowired
    private SysAgentMapper agentMapper;

    @Autowired
    private SysStoreMapper sysStoreMapper;


    /**
     * 查询报告列表列表
     */
    @Anonymous
//    @PreAuthorize("@ss.hasPermi('report:reportDetails:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysOrderOne orderOne,@RequestParam(name = "params[beginCreateTime]", required = false) Date beginCreateTime,
                              @RequestParam(name = "params[endCreateTime]", required = false) Date endCreateTime)
    {
        //数据隔离处理
        //判断应该返回哪些订单，如果为商户，则只返回自己dept下的背调订单，如果为代理商，则返回自己下所有的dept

        Long deptId = SecurityUtils.getDeptId();
        SysDept sysDept = deptMapper.selectDeptById(deptId);
        String types = sysDept.getType();
        List<SysOrderOne> list=null;

        if (beginCreateTime!=null) {
            orderOne.setBeginCreateTime(beginCreateTime);
        }
        if (endCreateTime!=null) {
            orderOne.setEndCreateTime(endCreateTime);
        }



        //封装状态
        Long orderStatus = orderOne.getOrderStatus();
        if (orderStatus==null) {
            List<Long> statusList = new ArrayList<>();
            statusList.add(3l);
            statusList.add(4l);
            statusList.add(5l);
            orderOne.setOrderStatus(null);
            orderOne.setStatusList(statusList);
        }



        //封装套餐状态
        //套餐信息封装
        if (orderOne.getPackageType()!=null) {
            List<Long> packageIdss =packageMapper.selectSysPackageByOnline(orderOne.getPackageType());
            orderOne.setPackageList(packageIdss);
        }


        if (types.equals("2")) {
            //说明是商户查
            orderOne.setDeptId(deptId);


            startPage();
            list = orderOneService.selectSysOrderOneList(orderOne);
        }
        else if (types.equals("1")) {
            //说明是代理商查
            List<SysAgent> agents = agentMapper.selectSysAgentByDeptId(deptId);
            if (CollectionUtils.isEmpty(agents)) {
                throw new ServiceException("代理商信息异常");
            }
            SysAgent sysAgent = agents.get(0);
            List<SysStore> sysStores = sysStoreMapper.selectSysStoreByAgentId(sysAgent.getId());

            if (CollectionUtils.isEmpty(sysStores)) {
                return getDataTable(sysStores);
            }

            List<Long> storeDeptIds = sysStores.stream().map(SysStore::getDeptId).collect(Collectors.toList());

            orderOne.setDeptIds(storeDeptIds);

            startPage();
            list = orderOneService.selectSysOrderOneList(orderOne);

        }
        else if (types.equals("0")) {
            //说明是管理员
            List<SysStore> sysStores = sysStoreMapper.selectSysStoreByAgentId(0l);

            if (CollectionUtils.isEmpty(sysStores)) {
                return getDataTable(sysStores);
            }

            List<Long> storeDeptIds = sysStores.stream().map(SysStore::getDeptId).collect(Collectors.toList());

            orderOne.setDeptIds(storeDeptIds);

            startPage();
            list = orderOneService.selectSysOrderOneList(orderOne);

        }



        if (CollectionUtils.isEmpty(list)) {
            return getDataTable(list);
        }

        for (SysOrderOne orderOnes : list) {
            orderOnes.setIdNumber(OrderUtils.maskIDCard(orderOnes.getIdNumber()));
            orderOnes.setPhone(OrderUtils.maskPhoneNumber(orderOnes.getPhone()));
        }

        List<Long> orderIds = list.stream().map(SysOrderOne::getId).collect(Collectors.toList());

        //根据id取查报告明细表
      List<SysReportDetails> reportDetails= reportDetailsMapper.selectSysReportDetailsByIds(orderIds);

        Map<Long,List<SysReportDetails>> reportMpas = new HashMap<>();

        for (SysReportDetails reportDetail : reportDetails) {

            reportMpas.put(reportDetail.getOrderId(),new ArrayList<SysReportDetails>());
        }
        for (SysReportDetails reportDetail : reportDetails) {

            reportMpas.get(reportDetail.getOrderId()).add(reportDetail);
        }

        ArrayList<SysReportVO> reportVOS= new ArrayList<>();
        for (SysOrderOne one : list) {
            SysReportVO sysReportVO = new SysReportVO();
            BeanUtils.copyProperties(one, sysReportVO);
            sysReportVO.setPerInfo(-1l);
            sysReportVO.setSocialSecurity(-1l);
            sysReportVO.setPerCredit(-1l);
            sysReportVO.setCommercial(-1l);
            sysReportVO.setCourtSue(-1l);
            sysReportVO.setEducation(-1l);

            List<SysReportDetails> reportDetails1 = reportMpas.get(one.getId());
            if (!CollectionUtils.isEmpty(reportDetails1)) {
            for (SysReportDetails sysReportDetails : reportDetails1) {
                String type = sysReportDetails.getType();
                Long surveyResult = sysReportDetails.getSurveyResult();
                if (type.equals("0")) {

                    if (sysReportVO.getPerInfo()<surveyResult) {
                        sysReportVO.setPerInfo(surveyResult);
                        continue;
                    }
                    continue;

                }
                if (type.equals("1")) {

                    if (sysReportVO.getSocialSecurity()<surveyResult) {
                        sysReportVO.setSocialSecurity(surveyResult);
                        continue;
                    }
                    continue;


                }
                if (type.equals("2")) {

                    if (sysReportVO.getSocialSecurity()<surveyResult) {
                        sysReportVO.setSocialSecurity(surveyResult);
                        continue;
                    }
                    continue;

                }
                if (type.equals("3") || type.equals("4") || type.equals("5") || type.equals("6") || type.equals("7") || type.equals("8")) {




                    if (sysReportVO.getPerCredit()< surveyResult) {
                        sysReportVO.setPerCredit(surveyResult);
                        continue;
                    }
                    continue;

                }

                if (type.equals("9")) {


                    if (sysReportVO.getCommercial()< surveyResult) {
                        sysReportVO.setCommercial(surveyResult);
                        continue;
                    }
                    continue;

                }
                if (type.equals("10")) {

                    if (sysReportVO.getCourtSue()< surveyResult) {
                        sysReportVO.setCourtSue(surveyResult);
                        continue;
                    }
                    continue;

                }
                if (type.equals("11") || type.equals("12")) {

                    if (sysReportVO.getEducation()< surveyResult) {
                        sysReportVO.setEducation(surveyResult);
                        continue;
                    }
                    continue;
                }


            }
        }
            reportVOS.add(sysReportVO);
        }

        //封装套餐的线上线下：
        List<Long> packageIds = new ArrayList<>(reportVOS.stream().map(SysReportVO::getSetmealId).collect(Collectors.toSet()));

        List<SysPackage> packages = packageMapper.selectSysPackageByIds(packageIds);
        Map<Long, String> collect = packages.stream().collect(Collectors.toMap(SysPackage::getId, c -> c.getLineStatus()));

        for (SysReportVO reportVO : reportVOS) {
            reportVO.setPackageType(collect.get(reportVO.getSetmealId()));
        }


        System.out.println(reportVOS.toString());
        return getDataTable(reportVOS);
    }

    /**
     * 导出报告列表列表
     */
    @PreAuthorize("@ss.hasPermi('report:reportDetails:export')")
    @Log(title = "报告列表", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysOrderOne orderOne,@RequestParam(name = "params[beginCreateTime]", required = false) Date beginCreateTime,
                       @RequestParam(name = "params[endCreateTime]", required = false) Date endCreateTime)
    {
        //数据隔离处理
        //判断应该返回哪些订单，如果为商户，则只返回自己dept下的背调订单，如果为代理商，则返回自己下所有的dept

        Long deptId = SecurityUtils.getDeptId();
        SysDept sysDept = deptMapper.selectDeptById(deptId);
        String types = sysDept.getType();
        List<SysOrderOne> list=null;

        if (beginCreateTime!=null) {
            orderOne.setBeginCreateTime(beginCreateTime);
        }
        if (endCreateTime!=null) {
            orderOne.setEndCreateTime(endCreateTime);
        }



        //封装状态
        Long orderStatus = orderOne.getOrderStatus();
        if (orderStatus==null) {
            List<Long> statusList = new ArrayList<>();
            statusList.add(3l);
            statusList.add(4l);
            statusList.add(5l);
            orderOne.setOrderStatus(null);
            orderOne.setStatusList(statusList);
        }



        //封装套餐状态
        //套餐信息封装
        if (orderOne.getPackageType()!=null) {
            List<Long> packageIdss =packageMapper.selectSysPackageByOnline(orderOne.getPackageType());
            orderOne.setPackageList(packageIdss);
        }


        if (types.equals("2")) {
            //说明是商户查
            orderOne.setDeptId(deptId);


            startPage();
            list = orderOneService.selectSysOrderOneList(orderOne);
        }
        else if (types.equals("1")) {
            //说明是代理商查
            List<SysAgent> agents = agentMapper.selectSysAgentByDeptId(deptId);
            if (CollectionUtils.isEmpty(agents)) {
                throw new ServiceException("代理商信息异常");
            }
            SysAgent sysAgent = agents.get(0);
            List<SysStore> sysStores = sysStoreMapper.selectSysStoreByAgentId(sysAgent.getId());

            if (CollectionUtils.isEmpty(sysStores)) {
                throw new ServiceException("数据为空");
            }

            List<Long> storeDeptIds = sysStores.stream().map(SysStore::getDeptId).collect(Collectors.toList());

            orderOne.setDeptIds(storeDeptIds);

            startPage();
            list = orderOneService.selectSysOrderOneList(orderOne);

        }
        else if (types.equals("0")) {
            //说明是管理员
            List<SysStore> sysStores = sysStoreMapper.selectSysStoreByAgentId(0l);

            if (CollectionUtils.isEmpty(sysStores)) {
                throw new ServiceException("数据为空");
            }

            List<Long> storeDeptIds = sysStores.stream().map(SysStore::getDeptId).collect(Collectors.toList());

            orderOne.setDeptIds(storeDeptIds);

            startPage();
            list = orderOneService.selectSysOrderOneList(orderOne);

        }



        if (CollectionUtils.isEmpty(list)) {
            throw new ServiceException("数据为空");
        }


        List<Long> orderIds = list.stream().map(SysOrderOne::getId).collect(Collectors.toList());

        //根据id取查报告明细表
        List<SysReportDetails> reportDetails= reportDetailsMapper.selectSysReportDetailsByIds(orderIds);

        Map<Long,List<SysReportDetails>> reportMpas = new HashMap<>();

        for (SysReportDetails reportDetail : reportDetails) {

            reportMpas.put(reportDetail.getOrderId(),new ArrayList<SysReportDetails>());
        }
        for (SysReportDetails reportDetail : reportDetails) {

            reportMpas.get(reportDetail.getOrderId()).add(reportDetail);
        }

        ArrayList<SysReportVO> reportVOS= new ArrayList<>();
        for (SysOrderOne one : list) {
            one.setUserName(one.getCreateBy());
            SysReportVO sysReportVO = new SysReportVO();
            BeanUtils.copyProperties(one, sysReportVO);
            sysReportVO.setPerInfo(-1l);
            sysReportVO.setSocialSecurity(-1l);
            sysReportVO.setPerCredit(-1l);
            sysReportVO.setCommercial(-1l);
            sysReportVO.setCourtSue(-1l);
            sysReportVO.setEducation(-1l);
            List<SysReportDetails> reportDetails1 = reportMpas.get(one.getId());
            if (!CollectionUtils.isEmpty(reportDetails1)) {
                for (SysReportDetails sysReportDetails : reportDetails1) {
                    String type = sysReportDetails.getType();
                    Long surveyResult = sysReportDetails.getSurveyResult();
                    if (type.equals("0")) {
                        if (sysReportVO.getPerInfo() != -1l && sysReportVO.getPerInfo() != 2l) {
                            continue;
                        }

                        sysReportVO.setPerInfo(surveyResult);
                        continue;

                    }
                    if (type.equals("1")) {
                        if (sysReportVO.getSocialSecurity() != -1l && sysReportVO.getSocialSecurity() != 2l) {
                            continue;
                        }

                        sysReportVO.setSocialSecurity(surveyResult);
                        continue;

                    }
                    if (type.equals("2")) {
                        if (sysReportVO.getSocialSecurity() != -1l && sysReportVO.getSocialSecurity() != 2l) {
                            continue;
                        }

                        sysReportVO.setSocialSecurity(surveyResult);
                        continue;

                    }
                    if (type.equals("3") || type.equals("4") || type.equals("5") || type.equals("6") || type.equals("7") || type.equals("8")) {
                        if (sysReportVO.getPerCredit() != -1l && sysReportVO.getPerCredit() != 2l) {
                            continue;
                        }

                        sysReportVO.setPerCredit(surveyResult);
                        continue;

                    }

                    if (type.equals("9")) {
                        if (sysReportVO.getCommercial() != -1l && sysReportVO.getCommercial() != 2l) {
                            continue;
                        }

                        sysReportVO.setCommercial(surveyResult);
                        continue;

                    }
                    if (type.equals("10")) {
                        if (sysReportVO.getCourtSue() != -1l && sysReportVO.getCourtSue() != 2l) {
                            continue;
                        }

                        sysReportVO.setCourtSue(surveyResult);
                        continue;

                    }
                    if (type.equals("11") || type.equals("12")) {
                        if (sysReportVO.getEducation() != -1l && sysReportVO.getEducation() != 2l) {
                            continue;
                        }

                        sysReportVO.setEducation(surveyResult);
                        continue;

                    }


                }
            }
            reportVOS.add(sysReportVO);
        }

        //封装套餐的线上线下：
        List<Long> packageIds = new ArrayList<>(reportVOS.stream().map(SysReportVO::getSetmealId).collect(Collectors.toSet()));

        List<SysPackage> packages = packageMapper.selectSysPackageByIds(packageIds);
        Map<Long, String> collect = packages.stream().collect(Collectors.toMap(SysPackage::getId, c -> c.getLineStatus()));

        for (SysReportVO reportVO : reportVOS) {
            reportVO.setPackageType(collect.get(reportVO.getSetmealId()));
        }


        ExcelUtil<SysReportVO> util = new ExcelUtil<SysReportVO>(SysReportVO.class);
        util.exportExcel(response, reportVOS, "报告列表数据");
    }

    /**
     * 获取报告列表详细信息
     */
    @PreAuthorize("@ss.hasPermi('report:reportDetails:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(sysReportDetailsService.selectSysReportDetailsById(id));
    }

    /**
     * 新增报告列表
     */
    @PreAuthorize("@ss.hasPermi('report:reportDetails:add')")
    @Log(title = "报告列表", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysReportDetails sysReportDetails)
    {
        return toAjax(sysReportDetailsService.insertSysReportDetails(sysReportDetails));
    }

    /**
     * 修改报告列表
     */
    @PreAuthorize("@ss.hasPermi('report:reportDetails:edit')")
    @Log(title = "报告列表", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysReportDetails sysReportDetails)
    {
        return toAjax(sysReportDetailsService.updateSysReportDetails(sysReportDetails));
    }

    /**
     * 删除报告列表
     */
    @PreAuthorize("@ss.hasPermi('report:reportDetails:remove')")
    @Log(title = "报告列表", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(sysReportDetailsService.deleteSysReportDetailsByIds(ids));
    }
}
